package net.luohuasheng.bee.proxy.jdbc;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;


/**
 * @author luohuasheng
 * @date 2020/4/17 08:43
 */
public class LoggingProxy {

    protected static ThreadLocal<LogCall> LOG_CALL = new ThreadLocal<>();

    public static void addLogCall(LogCall logCall) {
        LOG_CALL.set(logCall);
    }


    public static void removeLogCall() {
        LOG_CALL.remove();
    }

    public static LogCall get() {
        return LOG_CALL.get();
    }

    public interface LogCall {
        void debug(String text, boolean input);
    }


    public static void localPrint(Logger localLogger, String text, boolean input) {
        if (text.contains(":")) {
            String[] texts = text.split(":", 2);
            text = String.format("%11s", texts[0]) + ": " + texts[1];
        } else {
            text = String.format("%11s", text);
        }
        if (localLogger.isDebugEnabled()) {
            localLogger.debug((input ? "<==" : "==>") + text);
        }

    }

    public static void print(String text, boolean input) {
        if (LOG_CALL.get() != null) {
            LOG_CALL.get().debug(text, input);
        } else {
            String className = null;
            for (StackTraceElement stackTraceElement : Thread.currentThread().getStackTrace()) {
                if (stackTraceElement.getMethodName().contains("invoke")) {
                    break;
                }
                className = stackTraceElement.getClassName() + "." + stackTraceElement.getMethodName();
            }
            Logger localLogger = LoggerFactory.getLogger(className);
            localPrint(localLogger, text, input);
        }
    }
}
